package com.bolingcavalry.crm.contacts.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bolingcavalry.crm.aftersales.mapper.AfterSalesMapper;
import com.bolingcavalry.crm.contacts.mapper.ContactsMapper;
import com.bolingcavalry.crm.contacts.service.ContactsService;
import com.bolingcavalry.crm.serviceproblem.mapper.ServiveProblemMapper;
import com.bolingcavalry.crm.summaryorder.mapper.ServiceSummaryOrderMapper;
import com.bolingcavalry.crm.taskorder.mapper.ConfirmationMapper;
import com.bolingcavalry.crm.taskorder.mapper.TaskorderMapper;
import com.bolingcavalry.crm.utils.AUtils;
import com.dto.CustomerContactDTO;
import com.entity.aftersales.AfterSales;
import com.entity.customer.CustomerContacts;
import com.entity.serviceproblem.ServiceProblem;
import com.entity.summaryorder.ServiceSummaryOrder;
import com.entity.taskorder.ConfirmationOrder;
import com.entity.taskorder.TaskOrder;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vo.AfterSales.AfterSalesVO;
import com.vo.CustomerContactVO;
import com.vo.ServiceProblemVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ContactsServiceImpl implements ContactsService {
    @Autowired
    private ContactsMapper contactsMapper;
    @Autowired
    private AUtils aUtils;
    @Autowired
    private AfterSalesMapper afterSalesMapper;
    @Autowired
    private ServiveProblemMapper serviceProblemMapper;
    @Autowired
    private TaskorderMapper taskorderMapper;
    @Autowired
    private ServiceSummaryOrderMapper serviceSummaryOrderMapper;
    @Autowired
    private ConfirmationMapper confirmationMapper;

    //增加联系人
    @Override
    public boolean add(CustomerContactDTO customerContactDTO) {
        CustomerContacts customerContacts = new CustomerContacts();
        BeanUtils.copyProperties(customerContactDTO, customerContacts);
        customerContacts.setCreateTime(LocalDateTime.now());
        //判断当前客户公司下是否存在该联系人
        LambdaQueryWrapper<CustomerContacts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerContacts::getCustomerCompanyId, customerContacts.getCustomerCompanyId());
        queryWrapper.eq(CustomerContacts::getFullName, customerContacts.getFullName());
        queryWrapper.eq(CustomerContacts::getPhoneNumber, customerContacts.getPhoneNumber());
        CustomerContacts contacts = contactsMapper.selectOne(queryWrapper);
        //如果名称手机号都一致，则说明存在
        if(contacts != null){
            return false;
        }
        contactsMapper.insert(customerContacts);
        return true;
    }

    //删除
    @Override
    public boolean batchDelete(List<Long> ids) {
        //逻辑删除直接吧isdelete置为0
        LambdaQueryWrapper<CustomerContacts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(CustomerContacts::getId, ids);
        List<CustomerContacts> contacts = contactsMapper.selectList(queryWrapper);
        for (CustomerContacts contact : contacts) {
            contact.setIsDelete(0);
            if(contactsMapper.updateById(contact)<=0){
                return false;
            }
        }
        return true;
    }

    private boolean hasChildren(List<Long> ids) {
        LambdaQueryWrapper<TaskOrder> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(TaskOrder::getContactPersonId, ids);
        if(taskorderMapper.selectCount(queryWrapper1)>0){
            return false ;
        }
        LambdaQueryWrapper<ServiceSummaryOrder> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.in(ServiceSummaryOrder::getCustomerContactsId, ids);
        if(serviceSummaryOrderMapper.selectCount(queryWrapper2)>0){
            return false;
        }
        LambdaQueryWrapper<ConfirmationOrder> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.in(ConfirmationOrder::getContactPersonId, ids);
        if(confirmationMapper.selectCount(queryWrapper3)>0){
            return false;
        }
        return true;
    }

    //修改
    @Override
    public boolean update(CustomerContactDTO customerContactDTO) {
        CustomerContacts customerContacts = new CustomerContacts();
        BeanUtils.copyProperties(customerContactDTO, customerContacts);
        //判断当前客户公司下是否存在该联系人
        LambdaQueryWrapper<CustomerContacts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerContacts::getCustomerCompanyId, customerContacts.getCustomerCompanyId());
        queryWrapper.eq(CustomerContacts::getFullName, customerContacts.getFullName());
        queryWrapper.eq(CustomerContacts::getPhoneNumber, customerContacts.getPhoneNumber());
        CustomerContacts contacts = contactsMapper.selectOne(queryWrapper);
        //如果名称手机号都一致，则说明存在
        if(contacts != null){
            return false;
        }
        if(contactsMapper.updateById(customerContacts)>0){
            return true;
        }
        return false;
    }

    //查询
    @Override
    public CustomerContactVO get(Long id) {
        CustomerContacts customerContacts = contactsMapper.selectById(id);
        CustomerContactVO customerContactVO = new CustomerContactVO();
        if(null!=customerContacts)
        BeanUtils.copyProperties(customerContacts, customerContactVO);
        else return null;
        //如果公司id存在，根据公司id查询公司名称并赋值
        if(null!=customerContacts.getCustomerCompanyId()){
            customerContactVO.setCompanyName(aUtils.getCustomerCompanyNameById(customerContacts.getCustomerCompanyId()));
        }
        return customerContactVO;
    }

    @Override
    public IPage<CustomerContactVO> list(Integer pageNum, Integer pageSize, String customerCompanyName, String fullName, String phoneNumber) {
        IPage<CustomerContactVO> pageResult;

        if (pageSize == null) {
            // 查询全部数据，使用足够大的页面大小
            Page<CustomerContacts> page = new Page<>(1, 100000);
            pageResult = contactsMapper.list(page, customerCompanyName, fullName, phoneNumber);

            // 调整分页信息，使其更符合"查询全部"的语义
            pageResult.setPages(1);
            pageResult.setCurrent(1);
            pageResult.setSize(pageResult.getTotal());
        } else {
            // 正常分页查询
            Page<CustomerContacts> page = new Page<>(pageNum, pageSize);
            pageResult = contactsMapper.list(page, customerCompanyName, fullName, phoneNumber);
        }

        return pageResult;
    }


    @Override
    public List<CustomerContactVO> listByCustomerId(Long customerId) {
        LambdaQueryWrapper<CustomerContacts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerContacts::getCustomerCompanyId, customerId)
                .eq(CustomerContacts::getIsDelete, 1);
        List<CustomerContacts> contacts = contactsMapper.selectList(queryWrapper);
        List<CustomerContactVO> customerContactVOS = new ArrayList<>();
        for (CustomerContacts customerContacts: contacts) {
            CustomerContactVO customerContactVO = new CustomerContactVO();
            BeanUtils.copyProperties(customerContacts, customerContactVO);
            customerContactVO.setCompanyName(aUtils.getCustomerCompanyNameById(customerContacts.getCustomerCompanyId()));
            customerContactVOS.add(customerContactVO);
        }
        return customerContactVOS;

    }

    @Override
    @Transactional
    public boolean setPrimary(Long id) {
        //首先设置所有公司的联系人字段为0
        contactsMapper.setAllPrimary();
        if(contactsMapper.setPrimary(id)>0){
            return true;
        }
        return false;
    }

    /**
     * 根据公司id查询联系人列表
     * @param id
     * @return
     */
    @Override
    public List<CustomerContactVO> listByCustomerCompanyId(Long id) {
        return contactsMapper.listByCustomerCompanyId(id);
    }

    /**
     * 根据公司id查询售后列表
     * @param id
     * @return
     */
    @Override
    public List<AfterSalesVO> listByCustomerCompanyIdAfterSales(Long id) {
        LambdaQueryWrapper<AfterSales> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AfterSales::getCustomerId, id);
        List<AfterSales> afterSales = afterSalesMapper.selectList(queryWrapper);
        return afterSales.stream().map(aftersales -> {
            AfterSalesVO afterSalesVO = new AfterSalesVO();
            BeanUtils.copyProperties(aftersales, afterSalesVO);
            //设置客户公司名称id、任务接收人名称
            afterSalesVO.setCustomerName(aUtils.getCustomerCompanyNameById(aftersales.getCustomerId()));
            afterSalesVO.setCustomerCompanyId(aftersales.getCustomerId());
            //查询任务接收人列表
            afterSalesVO.setReceiverName(new ArrayList<>());
            for (Long l : afterSalesMapper.getReceiverName(aftersales.getOrderNumber())) {
                afterSalesVO.getReceiverName().add(aUtils.getUserNickNameByUserId(l));
            }
            return afterSalesVO;
        }).toList();
    }

    /**
     * 根据公司id查询服务问题列表
     * @param id
     * @return
     */
    @Override
    public List<ServiceProblemVO> listByCustomerCompanyIdServiceProblem(Long id) {
        LambdaQueryWrapper<ServiceProblem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ServiceProblem::getCustomerCompanyId, id);
        queryWrapper.eq(ServiceProblem::getIsDeleted, 1);
        List<ServiceProblem> serviceProblems = serviceProblemMapper.selectList(queryWrapper);
        return serviceProblems.stream().map(serviceProblem -> {
            ServiceProblemVO serviceProblemVO = new ServiceProblemVO();
            BeanUtils.copyProperties(serviceProblem, serviceProblemVO);
            serviceProblemVO.setCustomerCompanyName(aUtils.getCustomerCompanyNameById(serviceProblem.getCustomerCompanyId()));

            // 处理图片数据 - 复用ServiceProblemServiceImpl中的逻辑
            try {
                String photos = serviceProblemMapper.getPhotos(serviceProblem.getId());
                if (photos != null && !photos.isEmpty() && !photos.equals("[]")) {
                    // 解析 JSON 数组字符串为 List<String>
                    ObjectMapper objectMapper = new ObjectMapper();
                    List<String> photosList = objectMapper.readValue(photos, new TypeReference<List<String>>() {});
                    serviceProblemVO.setPhotos(photosList);
                } else {
                    // 如果没有图片数据，设置为空列表
                    serviceProblemVO.setPhotos(new ArrayList<>());
                }
            } catch (Exception e) {
                // 如果解析失败，设置为空列表
                serviceProblemVO.setPhotos(new ArrayList<>());
            }

            return serviceProblemVO;
        }).toList();
    }

}
